<template>
  <div class="container">
    <el-form
      :disabled="isCheck"
      :model="formData"
      :rules="$rules"
      label-width="7rem"
      ref="taskInfoRef"
      class="pr-2 pl-2"
      status-icon
    >
      <div class="row">
        <div class="col-1 mr-2">
          <el-form-item :label="$language.local('customerName')" prop="MID">
            <select-merchantid v-model="formData.MID"></select-merchantid>
          </el-form-item>
          <el-form-item :label="$language.local('任务类型')" prop="ServiceType">
            <select-servicetype
              :merchantId="formData.MID"
              v-model="formData.ServiceType"
            ></select-servicetype>
          </el-form-item>

          <el-form-item :label="$language.local('项目名称')" prop="projectName">
            <xy-input v-model="formData.projectName" clearable></xy-input>
          </el-form-item>

          <el-form-item
            :label="$language.local('recruitPerson')"
            prop="recruitPerson"
          >
            <select-recruitperson
              v-model="formData.recruitPerson"
            ></select-recruitperson>
          </el-form-item>
          <el-form-item :label="$language.local('开始日期')" prop="BegTime">
            <select-date v-model="formData.BegTime"></select-date>
          </el-form-item>
          <el-form-item
            :label="$language.local('结束日期')"
            prop="EndTime"
            :rules="EndTimeRule"
          >
            <select-date v-model="formData.EndTime"></select-date>
          </el-form-item>
          <el-form-item :label="$language.local('Amount')" prop="Amount">
            <!-- <xy-input
              type="number"
              v-model="formData.Amount"
              clearable
            ></xy-input> -->
            <xy-decimal v-model="formData.Amount"></xy-decimal>
          </el-form-item>

          <el-form-item
            :label="$language.local('SettlementModes')"
            prop="SettlementModes"
          >
            <!-- <xy-input v-model="formData.SettlementModes" clearable></xy-input> -->
            <!-- <el-select v-model="formData.SettlementModes" clearable filterable>
              <el-option
                v-for="item in settlementModes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select> -->
            <select-settlementmode
              v-model="formData.SettlementModes"
            ></select-settlementmode>
          </el-form-item>
          <el-form-item
            v-if="formData.SettlementModes == 4"
            prop="otherSettlementModes"
          >
            <xy-input v-model="formData.otherSettlementModes"></xy-input>
          </el-form-item>
          <el-form-item v-if="ServiceContents.length > 0">
            <el-select
              v-model="ServiceContent"
              placeholder="可选择参考范例"
              class="select-servicecontent"
              @change="ServiceContentChange"
            >
              <el-option
                v-for="item in ServiceContents"
                :key="item.Id"
                :label="item.ModelTitle"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="col-1 pr-2">
          <el-card class="invoice-instructions col-1" shadow="never">
            <div class="title">
              <h3>
                <i class="el-icon-info"></i> {{ $language.local("remark") }}:
              </h3>
            </div>

            <p class="text item">
              1、工作内容的描述不能有如下字眼：<em class="red"
                >工资、补贴、津贴、福利、劳务、销售、经纪、工程安装、装修、装饰、清包工</em
              >等字眼；
            </p>
            <p class="text item">
              2、工作内容描述不录入具体人员姓名、金额数字等详细内容；
            </p>
            <p class="text item">
              3、所有带
              <em class="red"> * </em>
              号的均为必填项，必须填写完整才能提交保存。
            </p>

            <p class="text item">如有疑问请联系平台客服人员。</p>
          </el-card>
        </div>
      </div>
      <el-form-item :label="$language.local('工作内容')" prop="WorkContent">
        <xy-input
          type="textarea"
          :autosize="{ minRows: 3 }"
          v-model="formData.WorkContent"
          clearable
        ></xy-input>
      </el-form-item>
      <el-form-item
        prop="RecruitmentRequirements"
        :label="$language.local('RecruitmentRequirements')"
      >
        <xy-input
          type="textarea"
          :autosize="{ minRows: 3 }"
          v-model="formData.RecruitmentRequirements"
          clearable
        ></xy-input
      ></el-form-item>
      <el-form-item :label="$language.local('附件')" prop="attFilePath">
        <span class="info">(可选项) 关于任务的需求文档</span>
        <upload-file
          v-model="formData.attFilePath"
          :name="formData.attFileName"
          :on-success="onSuccess"
        ></upload-file>
      </el-form-item>
    </el-form>
    <div class="form-footer pb-3">
      <el-button size="mini" @click="$router.go(-1)">{{
        $language.local("返回")
      }}</el-button>
      <template v-if="action == 'Check'">
        <el-button
          size="mini"
          class=""
          type="danger"
          @click="showReasonDialog"
          >{{ $language.local("不通过") }}</el-button
        >
        <el-button size="mini" type="success" @click="onCheck(1)">{{
          $language.local("通过")
        }}</el-button>

        <!-- #region 审核原因 -->
        <el-dialog
          :title="$language.local('Reason')"
          :visible.sync="inputReasonVisible"
        >
          <el-form
            ref="ReasonRef"
            :model="formData"
            :rules="$rules"
            status-icon
          >
            <el-form-item prop="Reason">
              <xy-input v-model="formData.Reason" clearable></xy-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="onCheck(2)"
              >确 定</el-button
            >
          </div>
        </el-dialog>
        <!-- #endregion -->
      </template>
      <el-button
        size="mini"
        v-else
        type="primary"
        @click="onSubmit('taskInfoRef')"
        >{{ $language.local("确定") }}</el-button
      >
    </div>
  </div>
</template>

<script>
export default {
  data() {
    const validateEndTime = (rule, value, callback) => {
      if (!this.formData.BegTime) {
        callback(new Error("请输入开始时间！"));
        return;
      }
      const begTime = new Date(this.formData.BegTime);
      const endTime = new Date(value);
      if (endTime.compare(begTime)) {
        callback();
      } else {
        callback(new Error("请输入大于开始时间的日期！"));
      }
    };
    return {
      action: "Create",
      apiName: "/api/ServiceProject/Create",
      merchant: null,
      formData: {
        MID: null,
        SID: "",
        ServiceType: "",
        PostName: "",
        projectName: "",
        recruitPerson: 1,

        WorkContent: "",
        PerformanceFeeSettlementRules: "",

        ServiceName: "",
        BegTime: new Date().toLocaleDateString(),
        EndTime: "",
        Amount: null,

        attFileName: null,
        attFilePath: null,
        SettlementModes: "",
        otherSettlementModes: "",
        RecruitmentRequirements: "",
        checker: "",
        checkstatus: "",

        Reason: "",
      },
      attFileList: null,
      isCheck: false,
      inputReasonVisible: false,

      EndTimeRule: [
        { required: true, message: "不能为空", trigger: "blur" },
        { validator: validateEndTime, trigger: "blur" },
      ],
      ServiceContent: "",
      ServiceContents: [],
    };
  },
  watch: {
    "formData.ServiceType": {
      async handler(newValue) {
        try {
          const response = await this.$http.get(
            `/api/ServiceProject/GetContentModel?ServiceContent=${newValue}`
          );
          console.log(response);
          this.ServiceContents = response.data.Data;
        } catch (error) {
          console.log(error);
        }
      },
    },
  },
  created() {
    this.onConfig();
  },
  methods: {
    async onConfig() {
      let { id } = this.$route.query;

      if (!id) {
        this.$router.replace("/ServiceProjectList");
        return;
      }

      let item = null;
      try {
        item = await this.getServiceProjectById(id);
      } catch (error) {
        console.error(error);
        this.$router.replace("/ServiceProjectList");
        throw error;
      }
      console.log(item);

      if (!item) {
        console.log(123);
        this.$router.replace("/ServiceProjectList");
        return;
      }

      this.formData = {
        ...this.formData,
        ...item,
      };

      //  if (this.formData.attFilePath) {
      //     let name = this.formData.attFilePath.replace(/.+\//, "");
      //     console.log(name);
      //     if (name) {
      //       this.attFileList = [{ name, url: this.formData.attFilePath }];
      //     }
      //   }
    },
    async getServiceProjectById(id) {
      let response = await this.$http.get(`/api/ServiceProject/GetModel/${id}`);
      return response.data.Data;
    },
    onSuccess(e) {
      console.log(e);
      this.formData.attFileName = e.docname;
    },
    showReasonDialog() {
      this.inputReasonVisible = true;
    },
    async onCheck(check) {
      if (check == 2) {
        await this.$refs["ReasonRef"].validate();
      }
      let response = await this.$http.post(
        `/api/ServiceProject/Check/${this.formData.ID}?checkstatus=${check}&Reason=${this.formData.Reason}`
      );
      console.log(response);
      this.$message.success("审核成功");
      this.$router.go(-1);
    },
    async onSubmit(formName) {
      console.log(this.formData);
      this.$refs[formName].validate(async (valided, err1) => {
        if (!valided) {
          let keys = Object.keys(err1);
          this.$message.error(
            this.$language.local(err1[keys[0]][0].field) +
              this.$language.local(err1[keys[0]][0].message)
          );
          return;
        }

        try {
          let response = await this.$http.post(this.apiName, this.formData);
          console.log(response);
          this.$message.success("成功");
          this.$router.go(-1);
        } catch (error) {
          console.error(error);
        }
      });
    },
    ServiceContentChange(e) {
      console.log(e);
      this.formData.WorkContent = e.ModelContent;
      this.formData.RecruitmentRequirements = e.RRContent;
    },
  },
};
</script>

<style lang="less" scoped>
.el-select {
  width: 100%;
}
.row {
  align-items: flex-start;
  width: 100%;
}
.select-servicecontent {
  color: gray;
}
</style>
